/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/

namespace Votations.NSurvey.WebAdmin.UserControls
{
	using System;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using Votations.NSurvey;
	using Votations.NSurvey.Data;
	using Votations.NSurvey.DataAccess;
	using Votations.NSurvey.BusinessRules;
	using Votations.NSurvey.Enums;
	using Microsoft.VisualBasic;

	/// <summary>
	/// Survey data CU methods
	/// </summary>
	public partial class FilterOptionControl : UserControl
	{
		public event EventHandler OptionChanged;

		protected System.Web.UI.WebControls.TextBox TextBox1;
		protected System.Web.UI.WebControls.DropDownList DropDownList1;

		/// <summary>
		/// Id of the answer type to edit
		/// if no id is given put the 
		/// usercontrol in creation mode
		/// </summary>
		public int FilterId
		{
			get { return (ViewState["FilterId"]==null) ? -1 : int.Parse(ViewState["FilterId"].ToString()); }
			set { ViewState["FilterId"] = value; }
		}

		/// <summary>
		/// Id of the survey to which the type belongs
		/// </summary>
		public int SurveyId
		{
			get { return (ViewState["SurveyID"]==null) ? -1 : int.Parse(ViewState["SurveyID"].ToString()); }
			set { ViewState["SurveyID"] = value; }
		}


		protected void Page_Load(object sender, System.EventArgs e)
		{
			LocalizePage();

			MessageLabel.Visible = false;

			// Check if any answer type id has been assigned
			if (FilterId == -1)
			{
				SwitchToCreationMode();
			}
			else
			{
				SwitchToEditionMode();
			}
		}


		private void LocalizePage()
		{
			FilterNameLabel.Text = ((PageBase)Page).GetPageResource("FilterNameLabel");
			RuleOperatorLabel.Text = ((PageBase)Page).GetPageResource("RuleOperatorLabel");
			if (!Page.IsPostBack)
			{
				LogicalOperatorDropDownList.Items.Add(new ListItem(((PageBase)Page).GetPageResource("AndOperator"),"0"));
				LogicalOperatorDropDownList.Items.Add(new ListItem(((PageBase)Page).GetPageResource("OrOperator"),"1"));
			}
			NewRuleTitle.Text = ((PageBase)Page).GetPageResource("NewRuleTitle");
			QuestionLabel.Text = ((PageBase)Page).GetPageResource("QuestionLabel");
			AnswerLabel.Text = ((PageBase)Page).GetPageResource("AnswerLabel");
			FilterText.Text = ((PageBase)Page).GetPageResource("FilterText");
			FilterRulesTitle.Text = ((PageBase)Page).GetPageResource("FilterRulesTitle");
			AddRuleButton.Text = ((PageBase)Page).GetPageResource("AddRuleButton");
			UpdateFilterButton.Text = ((PageBase)Page).GetPageResource("UpdateFilterButton");
			DeleteFilterButton.Text = ((PageBase)Page).GetPageResource("DeleteFilterButton");
			CreatefilterButton.Text = ((PageBase)Page).GetPageResource("CreatefilterButton");
		}

		/// <summary>
		/// Setup the control in creation mode
		/// </summary>
		private void SwitchToCreationMode()
		{
			// Creation mode
			filtertitle.Text = ((PageBase)Page).GetPageResource("AddNewFilterTitle");
			CreatefilterButton.Visible = true;
			EditplaceHolder.Visible = false;
			UpdateFilterButton.Visible = false;
			DeleteFilterButton.Visible = false;
		}

		/// <summary>
		/// Setup the control in edition mode
		/// </summary>
		private void SwitchToEditionMode()
		{
			filtertitle.Text = ((PageBase)Page).GetPageResource("EditFilterTitle");
			CreatefilterButton.Visible = false;
			EditplaceHolder.Visible = true;
			UpdateFilterButton.Visible = true;
			DeleteFilterButton.Visible = true;
		}
		
		/// <summary>
		/// Get the current DB data and fill 
		/// the fields with them
		/// </summary>
		public void BindFields()
		{
			FilterData filterData = new Filters().GetFilterById(FilterId);
			FilterNameTextBox.Text = filterData.Filters[0].Description;
			LogicalOperatorDropDownList.SelectedValue = filterData.Filters[0].LogicalOperatorTypeID.ToString();
		
			RulesRepeater.DataSource = new Filters().GetRulesForFilter(FilterId);
			RulesRepeater.DataMember = "FilterRules";
			RulesRepeater.DataBind();

			QuestionFilterDropdownlist.DataSource = new Questions().GetAnswerableQuestionList(SurveyId);
			QuestionFilterDropdownlist.DataTextField = "QuestionText";
			QuestionFilterDropdownlist.DataValueField = "QuestionID";
			QuestionFilterDropdownlist.DataBind();
			QuestionFilterDropdownlist.Items.Insert(0, new ListItem(((PageBase)Page).GetPageResource("SelectQuestionMessage"), "-1"));
		
			AddRuleButton.Enabled = false;
			AnswerLabel.Visible = false;
			AnswerFilterDropdownlist.Visible = false;
			TextFilterTextbox.Visible = false;
			FilterText.Visible = false;
		}


		protected string FormatRule(string questionText, string answerText, string textFilter )
		{
			if (answerText.Length == 0)
			{
				return string.Format(((PageBase)Page).GetPageResource("FilterRuleNoAnswer"),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")));
			}
			else if (textFilter.Length == 0)
			{
				return string.Format(((PageBase)Page).GetPageResource("FilterRuleAnswer"),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")));
			}
			else 
			{
				return string.Format(((PageBase)Page).GetPageResource("FilterRuleAnswerWithText"),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
					Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(textFilter, "<[^>]*>", " ")));
			}
		}

		protected void QuestionFilterDropdownlist_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (QuestionFilterDropdownlist.SelectedValue != "-1")
			{
				AddRuleButton.Enabled = true;
				AnswerLabel.Visible = true;
				AnswerFilterDropdownlist.Visible = true;
				BindAnswerDropDownList();
			}
			else
			{
				AddRuleButton.Enabled = true;
				AnswerLabel.Visible = false;
				AnswerFilterDropdownlist.Items.Clear();
				AnswerFilterDropdownlist.Visible = false;
				TextFilterTextbox.Visible = false;
				TextFilterTextbox.Text = string.Empty;
				FilterText.Visible = false;
			}
		}

		/// <summary>
		/// Bind the list and mark field answer 
		/// with a negative answer id value
		/// </summary>
		private void BindAnswerDropDownList()
		{
			AnswerData answers = new Answers().GetAnswersList(int.Parse(QuestionFilterDropdownlist.SelectedValue));
			AnswerFilterDropdownlist.Items.Clear();
			AnswerFilterDropdownlist.Items.Add(new ListItem(((PageBase)Page).GetPageResource("AnyAnswerMessage"), "0"));

			foreach (AnswerData.AnswersRow answerRow in answers.Answers)
			{
				if ((((AnswerTypeMode)answerRow.TypeMode & AnswerTypeMode.Field) > 0) ||
					(((AnswerTypeMode)answerRow.TypeMode & AnswerTypeMode.Custom) > 0) ||
					(((AnswerTypeMode)answerRow.TypeMode & AnswerTypeMode.DataSource) > 0))
				{
					// Mark field answer with a negative answerid
					AnswerFilterDropdownlist.Items.Add(new ListItem(answerRow.AnswerText + " " + 
						((PageBase)Page).GetPageResource("TextEntryInfo"), (-answerRow.AnswerId).ToString()));
				}
				else
				{
					AnswerFilterDropdownlist.Items.Add(new ListItem(answerRow.AnswerText + " " + 
						((PageBase)Page).GetPageResource("SelectionInfo"), answerRow.AnswerId.ToString()));
				}
			}
		}

		protected void AnswerFilterDropdownlist_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (int.Parse(AnswerFilterDropdownlist.SelectedValue) < 0)
			{
				TextFilterTextbox.Visible = true;
				FilterText.Visible = true;
			}
			else
			{
				TextFilterTextbox.Text = string.Empty;
				TextFilterTextbox.Visible = false;
				FilterText.Visible = false;
			}
		}
		#region Web Form Designer generated code

		private void InitializeComponent()
		{
			this.RulesRepeater.ItemCommand += new System.Web.UI.WebControls.RepeaterCommandEventHandler(this.RulesRepeater_ItemCommand);

		}
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		


		#endregion

		protected void AddRuleButton_Click(object sender, System.EventArgs e)
		{
			FilterRuleData filterRuleData = new FilterRuleData();
			FilterRuleData.FilterRulesRow filterRule = filterRuleData.FilterRules.NewFilterRulesRow();
			
			int questionId = int.Parse(QuestionFilterDropdownlist.SelectedValue),
				answerId = int.Parse(AnswerFilterDropdownlist.SelectedValue);
			if (answerId == 0)
			{
				filterRule.SetAnswerIdNull();
			}
			else if ( answerId < 0)
			{
				filterRule.AnswerId  = -answerId;
			}
			else
			{
				filterRule.AnswerId = answerId;
			}

			filterRule.QuestionId = questionId;
			if (TextFilterTextbox.Visible)
			{
				filterRule.TextFilter = TextFilterTextbox.Text;
			}
			filterRule.FilterId = FilterId;
			filterRuleData.FilterRules.AddFilterRulesRow(filterRule);
			new Filter().AddRule(filterRuleData);
			MessageLabel.Visible = true;
			MessageLabel.Text = ((PageBase)Page).GetPageResource("FilterRuleAddedMessage");
			BindFields();
		}

        
		private void RulesRepeater_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
			new Filter().DeleteRule(int.Parse(e.CommandArgument.ToString()));
			MessageLabel.Visible = true;
			MessageLabel.Text = ((PageBase)Page).GetPageResource("FilterRuleDeletedMessage");
			BindFields();
		}

		protected void DeleteFilterButton_Click(object sender, System.EventArgs e)
		{
			new Filter().DeleteFilter(FilterId);
			MessageLabel.Visible = true;
			MessageLabel.Text = ((PageBase)Page).GetPageResource("FilterDeletedMessage");
			this.Visible = false;
			OnOptionChanged();
		}

		protected void OnOptionChanged()
		{
			if (OptionChanged != null)
			{
				OptionChanged(this, EventArgs.Empty);
			}
		}

		protected void UpdateFilterButton_Click(object sender, System.EventArgs e)
		{
			if (FilterNameTextBox.Text.Length == 0)
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidFilterDescriptionMessage");
			}
			else
			{
				FilterData filterData = new FilterData();
				FilterData.FiltersRow filterRow = filterData.Filters.NewFiltersRow();
				filterRow.LogicalOperatorTypeID = short.Parse(LogicalOperatorDropDownList.SelectedValue);
				filterRow.Description = FilterNameTextBox.Text;
				filterRow.FilterId = FilterId;
				filterData.Filters.AddFiltersRow(filterRow);
				new Filter().UpdateFilter(filterData);
				MessageLabel.Visible = true;
				MessageLabel.Text = ((PageBase)Page).GetPageResource("FilterUpdatedMessage");
			}
		}

		protected void CreatefilterButton_Click(object sender, System.EventArgs e)
		{
			if (FilterNameTextBox.Text.Length == 0)
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidFilterDescriptionMessage");
			}
			else
			{
				FilterData filterData = new FilterData();
				FilterData.FiltersRow filterRow = filterData.Filters.NewFiltersRow();
				filterRow.LogicalOperatorTypeID = short.Parse(LogicalOperatorDropDownList.SelectedValue);
				filterRow.Description = FilterNameTextBox.Text;
				filterRow.SurveyId = SurveyId;
				filterData.Filters.AddFiltersRow(filterRow);
				new Filter().AddFilter(filterData);
				UINavigator.NavigateToFilterEditor(SurveyId, ((PageBase)Page).MenuIndex);
			}
		}
	}
}
